﻿namespace CSharpHelpers.IOs
{
    class CRCHelper
    {
        //调用这个方法参数一是要算crc的字节数组，参数二是用前几个算
        public static void CalculateCRC(byte[] pByte)
        {
            if (pByte.Length < 3)
            {
                return;
            }

            ushort sum;
            CalculateCRC(pByte, pByte.Length - 2, out sum);
            pByte[pByte.Length - 1] = (byte)((sum & 0xFF00) >> 8);
            pByte[pByte.Length - 2] = (byte)(sum & 0xFF);
        }

        private static void CalculateCRC(byte[] pByte, int nNumberOfBytes, out ushort pChecksum)
        {
            int nBit;
            ushort nShiftedBit;
            pChecksum = 0xFFFF;

            for (int nByte = 0; nByte < nNumberOfBytes; nByte++)
            {
                pChecksum ^= pByte[nByte];
                for (nBit = 0; nBit < 8; nBit++)
                {
                    if ((pChecksum & 0x1) == 1)
                    {
                        nShiftedBit = 1;
                    }
                    else
                    {
                        nShiftedBit = 0;
                    }
                    pChecksum >>= 1;
                    if (nShiftedBit != 0)
                    {
                        pChecksum ^= 0xA001;
                    }
                }
            }
        }
    }
}
